package day_2022_9_to_12.Day;

import java.util.*;

/**
 * @author haomin
 * @date 2022/09/04 22:29
 **/
public class Day2_6_Offer48_LengthOfLongestSubstring {
    class Solution1 {
        public int lengthOfLongestSubstring(String s) {
            if(s == null) return 0;
            int maxLen = 0, start = 0;
            Map<Character, Integer> map = new HashMap<>();
            for(int i = 0; i < s.length(); ++i){
                char c = s.charAt(i);
                if(map.containsKey(c)){
                    start = Math.max(map.get(c)+1, start);
                }
                maxLen = Math.max(i - start + 1, maxLen);
                // 如果出现相同c,有更新c下标的作用
                map.put(c, i);
            }
            return maxLen;
        }
    }
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int left = 0, right = 0, maxLen = 0;
            Set<Character> set = new HashSet<>();
            while(right < s.length()){
                char c = s.charAt(right);
                if(set.contains(c)){
                    set.remove(s.charAt(left));
                    left++;
                }
                set.add(c);
                maxLen = Math.max(right-left+1, maxLen);
                right++;
            }
            return maxLen;
        }
    }
}